package chuanglan

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

var (
	SERVER_HOST = "http://smssh1.253.com/msg/send/json"
)

type Config struct {
	Account string
	Passwd string
}
type ChuangLan struct {
	conf *Config
}
type Msg struct {
	Sign string `json:"sign"`
	Content string `json:"content"`
	Mobiles string `json:"mobiles"`
}
type PostField struct {
	Account string `json:"account"`
	Password string `json:"password"`
	Msg string `json:"msg"`
	Phone string `json:"phone"`
	Report string `json:"report"`
}
type Result struct {
	Code string `json:"code"`
	Msg string `json:"errorMsg"`
	MsgId string `json:"msgId"`
}
func NewMsg(orderId int64, sign,content,mobiles string) Msg {
	return Msg{
		Sign: sign,
		Content: content,
		Mobiles: mobiles,
	}
}

func NewChuangLan(conf Config) *ChuangLan{
	return &ChuangLan{conf: &conf}
}
func (c *ChuangLan) Send(msg Msg) (msgId string, err error) {
	content := url.QueryEscape(msg.Content)
	field := PostField{
		Account:  c.conf.Account,
		Password: c.conf.Passwd,
		Msg:      content,
		Phone:    msg.Mobiles,
		Report:   "true",
	}
	data,_ := json.Marshal(field)
	client := http.Client{
		Timeout: time.Second * 3,
	}
	headers := map[string]string{
		"Content-Type": "application/json; charset=utf-8",
		"Accept":"application/json",
	}
	req,err := http.NewRequest("POST",SERVER_HOST,strings.NewReader(string(data)))
	if err != nil {
		return
	}
	for key, header := range headers {
		req.Header.Set(key, header)
	}
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	var result Result
	err = json.Unmarshal(body,&result)
	if err != nil {
		return
	}
	if result.Code == "0" {
		msgId = result.MsgId
		return
	}
	err = fmt.Errorf("%s|%s",result.Code,result.Msg)
	return
}